<template>
  <div>
      <el-card>
        <div class="en">
          <el-button type="primary" plain size="big" @click="handleAdd('searchFrom')" >添加</el-button>
          <el-button type="primary" @click="fetchData" plain size="big" icon="el-icon-menu">列表</el-button>
          <el-button  type="primary" @click="search" plain size="big" icon="el-icon-search">查找</el-button>
        </div>
        <div class="ry">
          <el-tabs v-model="activeName" @tab-click="handleClick"  tab-position="top">
            <el-tab-pane label="全部人员" name="0"/>
            <el-tab-pane
              :key="index"
              v-for="(item,index) in typeList"
              :label="item ==1?'系统人员':item==2?'企业人员':item==3?'备案人员':item==4?'禁用人员':''"
              :name="(index+1).toString()">
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-card>
    <div>
      <el-card style="position: relative">
        <el-row>
          <el-col :span="12">
            <div id="chart" style="width: 800px; height: 400px;position: relative"/>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="20" style="margin-top: 80px;margin-left: 50px">
              <el-col :span="4" v-for="(item) in retDate">
                  <el-statistic
                    :value="item.value"
                    :title="item.name">
                  </el-statistic>
                </el-col>
            </el-row>
            <el-row>
              <el-col :span="4"    v-for="(item) in retDate" style="margin-top: 50px;margin-left: 15px">
              <el-statistic
                :precision="2"
                :value="item.value/retDate[0].value * 100 "
                title="占比">
                <i slot="suffix">%</i>
              </el-statistic>
            </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-card>



      <el-table
        :data="peopleList"
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column type="selection" width="100" align="center"/>
        <el-table-column
          prop="id"
          label="序号"
          align="center"
          width="180">
        </el-table-column>
        <el-table-column
          prop="type "
          align="center"
          label="人员类型"
          width="180">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type == 1?'primary':scope.row.type == 2?'success':scope.row.type == 3?'warning':scope.row.type == 4?'danger':''">
              {{scope.row.type == 1?'系统人员':scope.row.type == 2?'企业人员':scope.row.type == 3?'备案人员':scope.row.type == 4?'禁用人员':''}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          align="center"
          label="人员名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="idCard"
          align="center"
          label="身份证号"
          width="250">
        </el-table-column>
        <el-table-column
          prop="phone"
          align="center"
          label="联系方式"
          width="220">
        </el-table-column>
        <el-table-column
          prop="createTime"
          align="center"
          label="开通日期"
          width="220">
        </el-table-column>
        <el-table-column
          prop="status"
          align="center"
          label="账户情况"
          width="220">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.status == 1?'禁用':'启用'" >
              <el-switch
                v-model="scope.row.status ==1"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="handleStatus(scope.row)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="220">
          <template slot-scope="scope">
            <el-button type="primary" @click="findPassword(scope.row)">重置密码</el-button>
          </template>

        </el-table-column>
      </el-table>
      <el-dialog title="重置密码" :visible.sync="dialogVisible">
        <el-form :model="management" :rules="managementRules" ref="managementRulesForm">
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
            <el-input v-model="management.phone" disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="验证码" :label-width="formLabelWidth" prop="code">
            <el-col :span="11">
            <el-input v-model="management.code"></el-input>
            <el-button @click="handeleSend" type="primary">发送验证码</el-button>
            </el-col>

          </el-form-item>
          <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPassword">
            <el-input v-model="management.password"></el-input>
          </el-form-item>
          <div>
            <el-button type="primary" @click="resetPassword">确定</el-button>
            <el-button @click="handelCancel">取消</el-button>
          </div>
        </el-form>
      </el-dialog>
          <el-dialog title="添加人员" :visible.sync="dialogFormVisible">
            <el-form :model="management" :rules="managementRules" ref="managementRulesForm">
              <el-form-item label="姓名" :label-width="formLabelWidth" prop="username">
                <el-input v-model="management.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                <el-input v-model="management.password"></el-input>
              </el-form-item>
              <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
                <el-input v-model="management.phone"></el-input>
              </el-form-item>
              <el-form-item label="身份证号" :label-width="formLabelWidth" prop="idCard">
                <el-input v-model="management.idCard"></el-input>
              </el-form-item>
              <el-form-item label="邮件" :label-width="formLabelWidth" prop="email">
                <el-input v-model="management.email"></el-input>
              </el-form-item>
              <el-form-item label="头像" :label-width="formLabelWidth" prop="avatar" v-model="management.avatar">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  list-type="picture-card"
                  :http-request="uploadFile"
                  :show-file-list="true"
                  :file-list="fileList"
                  :on-change="handleChange"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                    <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                      <i class="el-icon-download"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                  </div>
                  <img v-if="avatar" :src="avatar" >
<!--                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
                </el-upload>
              </el-form-item>
              <el-form-item label="人员类型" :label-width="formLabelWidth" prop="type">
                <el-select v-model="management.type" placeholder="请选择类型">
                  <el-option label="系统人员" value="1"></el-option>
                  <el-option label="企业人员" value="2"></el-option>
                  <el-option label="备案人员" value="3"></el-option>
                  <el-option label="禁用人员" value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="handleData('managementRulesForm')">确 定</el-button>
            </div>
          </el-dialog>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNumber"
        :page-sizes="[5, 10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

  </div>



</template>

<script>

import { add, findPwd, getEcharts, getList, getType, sendrcode, updateById, upload } from '@/api/user'
import avatar from 'element-ui/packages/avatar'
import * as echarts from 'echarts'
export default {
  name: 'management',
  computed: {
    avatar() {
      return avatar
    }
  },
  data(){
    return {
      retDate:[],
      Loading: true,
      fileList:[],
      pageNumber: 1,
      pageSize: 5,
      currentPage: 1,
      total: 0,
      peopleList:[],
      activeName:'0',
      typeList:[],
      dialogVisible: false,
      disabled: false,
      JinYong:true,
      title:'',
      dialogExcelVisible:false,
      dialogFormVisible:false,//对话框是否隐藏
      management: {
        // id: '',
        // username: '',
        type:'',
        // phone:'',
        // idCard:'',
        // createTime:'',
        // status:'',
      },
      formLabelWidth: '120px',
      managementRules: {
        username: [
          {required: true, message: '用户名不能为空', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '电话不能为空', trigger: 'blur'},
          {min: 11, max: 11, message: '长度为11位', trigger: 'blur'}
        ],
        idCard: [
          {required: true, message: '身份证不能为空', trigger: 'blur'},
          {min: 18, max: 18, message: '长度为18位', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}
        ],
        type: [
          {required: true, message: '必须选择一个类型', trigger: 'blur'},
        ],
      },
    }
  },
  methods: {
    fetchData() {
      let params = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        id: this.management.id,
        username: this.management.username,
        type: this.type,
        phone: this.management.phone,
        idCard: this.management.idCard,
        createTime: this.management.createTime,
        status: this.management.status
      }
      getList(params).then(res => {
        let pageInfo = res.data;
        console.log(pageInfo)
        this.Loading = false;
        this.peopleList = pageInfo.records
        console.log()
          this.total = pageInfo.total
      })
    },
    getTypeList(){
      getType().then(res => {
        let pageInfo = res.data;
        console.log(pageInfo)
        this.Loading = false;
        this.typeList = pageInfo
        console.log(this.typeList)
      })
    },
    handleSizeChange(val) {
      this.pageSize = val;

    },
    handleStatus(row){
      let params = {
        id:row.id,
        status:row.status == 1 ? 0 : 1
      }
      updateById(params).then(res =>{
        if (res.data) {
          this.$message({
            message: '状态修改成功',
            type: 'success'
          });
        }
        this.fetchData()
      })
    },
    findPassword(row){
      this.title = '重置密码'
      this.dialogVisible = true
      this.management.phone = row.phone
    },
    handeleSend(){
      let params = {
        phone:this.management.phone
      }
      sendrcode(params).then(res =>{
        if (res.data) {
          this.$message({
            message: '验证码发送成功',
            type: 'success'
          });
        }
      })
    },
    handelCancel(){
      this.management = {}
      this.dialogVisible = false
    },
    resetPassword(formName){
      let params = {
        phone:this.management.phone,
        code:this.management.code,
        password:this.management.password
      }
      findPwd(params).then(res =>{
        if (res.data) {
          this.$message({
            message: '密码重置成功',
            type: 'success'
          });
          this.management = {}
          this.dialogVisible = false
        }
      })
    },
    handleRemove() {
      this.fileList = []
    },
    handlePictureCardPreview(file) {
      this.avatar = URL.createObjectURL(file.raw);
    },
    handleAvatarSuccess(res, file) {
      this.avatar = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleCurrentChange(val) {
      this.pageNumber = val;
      this.$nextTick(()=> {
        this.fetchData()
      })
    },
    handleClick() {
      this.type = this.activeName
      console.log(this.type)
      this.fetchData()
    },
    handleSelectionChange() {

    },
    cancel(){
      this.dialogFormVisible = false
      this.$nextTick(()=>{
        this.fileList = []
        this.$refs.managementRulesForm.resetFields()
      })
    },
    //打开新增对话框
    handleAdd() {
      this.title="添加人员"
      this.dialogFormVisible = true;

    },
    uploadFile(){
      const file = this.file
      const formData = new FormData()
      formData.append('file', file)
      if (this.file > 1){
        this.$message({
           message: '只能选择一个图片作为头像',
           type: 'error'
         })
         return
      }
      upload(formData).then(res => {
           this.management.avatar = res.data
        this.$message({
           message: '上传成功',
           type: 'success'
         })
      })
    },
    handleChange(file){
      this.file = file.raw
    },
    handleUpdate(row) {
      this.title="修改人员"
      this.dialogFormVisible = true;
      this.$nextTick(()=>{
        this.$refs.managementRulesForm.resetFields()
        this.management = row
      })
    },

    search() {
      this.fetchData()
    },
    handleData(formName) {
     if (this.title === "添加人员"){
       this.$refs[formName].validate((valid) => {
         if (valid) {
           add(this.management).then(res => {
             this.$message({
               message: '添加成功',
               type: 'success'
             })
             this.dialogFormVisible = false
             this.$nextTick(()=>{
               this.$refs.managementRulesForm.resetFields()
             })
             this.fetchData()
           })
         } else {
           return false
         }
       })
     } else if (this.title === "修改人员"){
       this.$refs[formName].validate((valid) => {
         if (valid) {
           add(this.management).then(res => {
             this.$message({
               message: '修改成功',
               type: 'success'
             })
             this.dialogFormVisible = false
             this.fetchData()
           })
         } else {
           return false
         }
       })
     }
    },
    initChart() {
     const chart = echarts.init(document.getElementById('chart'))
       getEcharts({type:this.type}).then(res => {
         this.retDate = res.data
         const option = {
           title: { text: '人员类型' },
           tooltip: { trigger: 'axis' },
           legend: { data: ['人员类型'] },
           xAxis: { data:this.retDate.map(item => item.name)},
           yAxis: {  },
           series: [
             {
             colorBy:'data',
             name: '人员类型',
             type: 'bar',
             data: this.retDate.map(item => item.value)
           }
           ]
         };
         chart.setOption(option);
       })
    }
  },

  created() {//生命周期函数
    this.fetchData()//发请求查数据
    this.getTypeList()
  },
  mounted() {
    this.initChart()
  },
}
</script>
<style scoped>
.en{
  margin-left: 1100px;
  margin-top: -10px;
  prsition: 'relative';

}
.ry{
  margin-top: -40px;
  width: 800px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-right: 50px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
